<?php

namespace app\admin\controller;

use app\admin\model\AuthRule;

/**
 * Class Automatic 自动生成权限类
 * @package app\admin\controller
 */
class Automatic extends Common
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
        return $this->fetch();
    }

    /**
     * @return mixed 查询改控制器的所有方法
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function query()
    {
        $name = input('post.name');
        $res = $this->validate(['name' => $name], ['name|控制器名称' => 'require']);
        if (true !== $res) {
            return xjson(403, $res);
        }
        $full_name = 'app\\admin\\controller\\' . $name;
        try {
            $reflect = new \ReflectionClass($full_name);
        } catch (\Exception $e) {
            return xjson(500, '控制器不存在(' . $full_name . '),请检查控制器是否拼写正确！');
        }
        $reflect_methods = $reflect->getMethods();
        $method = [];
        foreach ($reflect_methods as $reflect_method) {
            if ($reflect_method && $reflect_method->class == $full_name && $reflect_method->name != 'initialize' && $reflect_method->isPublic()) {
                $res = AuthRule::where('link', url('admin' . '/' . $name . '/' . $reflect_method->name))->find();
                if (!$res) {
                    $method['auth'][] = [
                        'name'=>'admin' . '/' . $name . '/' .$reflect_method->name,
                        'sorts'=>100,
                        'ismenu'=>0,
                        'status'=>1
                    ];
                }
            }
        }
        if(!isset($method['auth'])){
            return xjson(404,'该控制器已全部添加完成！');
        }
        //追加父级节点列表
        $m=new AuthRule();
        $treeList = $m->treeList();
        $method['parent']=$treeList;
        return xjson($method);
    }
    //快速添加模型插入方法
    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $count=0;
            $ids=[];
            foreach ($data['data'] as $d){
                $res=AuthRule::where('link',url($d['name']))->find();
                if(!$res){
                    $d['pid']=$data['pid'];
                    $d['link']=$d['name'];
                    $m=new AuthRule;
                    $m=$m->create($d);
                    $count++;
                    $ids[]=$m['id'];
                }
            }
            //为差集用户添加权限
            $ag=\app\admin\model\AuthGroup::find();
            $ag->rules=implode(',',array_merge(explode(',',$ag->rules),$ids));
            $ag->save();
            return xjson($count.'条记录更新成功！');
        }
        return xjson(404, '请求不被允许');
    }
}